<?php

class DataObject
{
	var $fields;
	var $data;
	var $name;
	var $table;
	
	function __construct($name, $table)
	{
		$this->name = $name;
		$this->table = $table;
		$this->fields = Array();
		$this->data = Array();
		
		// Get field names from the table
		$query = 'DESCRIBE ' . $table;
		$fields = mysql_query($query);
		
		while($field = mysql_fetch_assoc($fields))
		{
			$this->fields[] = $field['Field'];
		}
		
		@mysql_free_result($fields);
		
		$this->data = array_fill_keys($this->fields, NULL);
	}
	
	function load($field, $data)
	{
		$query = 'SELECT * FROM ' . $this->table . ' WHERE ' . $field . '="' 
		 . $data . '" LIMIT 1';
		$result = mysql_query($query);
		if(!mysql_num_rows($result))
		{
			@mysql_free_result($result);
			return false;
		}
		
		$data = mysql_fetch_assoc($result);
		foreach($this->fields as $field)
		{
			$this->data[$field] = $data[$field];
		}
		@mysql_free_result($result);
		
		return $this->dados['id'];
	}
	
	function list($order = 'id')
	{
		$return = Array();
		$query = 'SELECT * FROM ' . $this->table . ' ORDER BY ' . $order;
		$result = mysql_query($query);
		while($data = mysql_fetch_assoc($result))
		{
			$return[] = $data;			
		}
		@mysql_free_result($result);
		return $return;
	}
	
	function exists($field, $value)
	{
		$query = 'SELECT id FROM ' . $this->table . ' WHERE ' . $field . '="' 
			. $value . '" LIMIT 1';
		$result = mysql_query($query);
		$data = mysql_fetch_assoc($result);
		$return = $data['id'];
		@mysql_free_result($result);
		return $return ? $return : 0;
	}
	
	function field($field)
	{
		return $this->data[$field];
	}
	
	function id($id = NULL)
	{
		if($id) return $this->load('id', $id);
		return $this->data['id'];
	}
}